//
//  LLT_PlayViewController_LXM.m
//  CoderLLT
//
//  Created by 刘晓萌 on 15/12/18.
//  Copyright © 2015年 刘晓萌. All rights reserved.
//

#import "LLT_PlayViewController_LXM.h"
#import "LLT_VideoModel.h"
#import <AVOSCloud/AVOSCloud.h>
#import "UIViewController+LLT_LoginAndRegist_LXM.h"

@interface LLT_PlayViewController_LXM ()
@property (weak, nonatomic) IBOutlet UIWebView *playWebView;

@property (copy ,nonatomic) NSString *webWidth;
@property (copy ,nonatomic) NSString *webHeight;
@property (weak, nonatomic) IBOutlet UIButton *saveButton;

@property (nonatomic, assign) BOOL isCollect;

@property (nonatomic, strong) NSMutableArray *data;

@end

@implementation LLT_PlayViewController_LXM

#pragma mark --- 懒加载

-(NSMutableArray *)data
{
    if (!_data) {
        _data = [NSMutableArray new];
    }
    return _data;
}

#pragma mark --- 设置视图
- (void)viewDidLoad {
    [super viewDidLoad];
    self.webWidth = [NSString stringWithFormat:@"%lf",self.playWebView.frame.size.width+50];
    self.webHeight = [NSString stringWithFormat:@"%lf",self.playWebView.frame.size.height];
    [self makeWebView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [self containsTheVideos];
}

/**
 * 点击进入页面是否更改收藏按钮的样式
 */
-(void)changeButton
{
    //NSLog(@"");
    for (LLT_VideoModel *video in self.data) {
        if ([video.title isEqualToString:self.videoModel.title])
        {
            self.isCollect = YES;
        }else
        {
            self.isCollect = NO;
        }
    }
    
    if (!self.isCollect)
    {
        [self.saveButton setImage:[UIImage imageNamed:@"cshoucang"] forState:UIControlStateNormal];
    }else
    {
        [self.saveButton setImage:[UIImage imageNamed:@"cshoucang_holder"] forState:UIControlStateNormal];
    }
    
    [self.saveButton addTarget:self action:@selector(saveButton:) forControlEvents:UIControlEventTouchUpInside];
}

/**
 * 设置横竖屏
 */
-(BOOL)shouldAutorotate {
    return YES;
}
-(UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

/**
 * 设置webview
 */
-(void)makeWebView{
    NSString *htmlStr = [NSString stringWithFormat:@"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd\"><html><head><style>html,body {margin: 0px;background-color: #000;}#youkuplayer {width:%@px;height:%@px;margin-top: 150px;}</style></head><body><div id=\"youkuplayer\" style=\"width:%@px;height:%@px\"></div><script type=\"text/javascript\" src=\"http://player.youku.com/jsapi\">player = new YKU.Player('youkuplayer',{styleid: '1',client_id: '2b6ae57ced9f1faf',vid: '%@',embsig: ''});</script></body></html>",[NSString stringWithFormat:@"%lf",WIDTH],@"200",[NSString stringWithFormat:@"%lf",WIDTH],@"200",self.url];
    
    [self.playWebView loadHTMLString:htmlStr baseURL:[NSURL URLWithString:@"http://player.youku.com/jsapi"]];
}

/**
 *  返回上个页面
 *
 *  @param sender
 */
- (IBAction)didClickLeftBackButton:(UIButton *)sender {
    DissMissBack;
}

/**
 * 点击收藏按钮
 */
-(void)saveButton:(UIButton *)sender
{
    
    //NSLog(@"  %@  ",self.data);
    
    if (!self.isCollect) {
        
        AVObject *videos = [AVObject objectWithClassName:@"LLT_VideoModel"];
        videos[@"cuserName"] = [AVUser currentUser].mobilePhoneNumber;
        videos[@"title"] = self.videoModel.title;
        videos[@"segs"] = self.videoModel.segs;
        videos[@"create_time"] = self.videoModel.create_time;
        videos[@"thumb_img"] = self.videoModel.thumb_img;
        videos[@"avatar"] = self.videoModel.avatar;
        videos[@"username"] = self.videoModel.username;
        videos[@"play_times"] = self.videoModel.play_times;
        videos[@"url"] = self.videoModel.url;
        
        [videos saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [self showAlert:@"提 示" andAlertString:@"收藏成功"];
                [self.saveButton setImage:[UIImage imageNamed:@"cshoucang_holder"] forState:UIControlStateNormal];
                self.isCollect = YES;
            }else{
                //NSLog(@"%@",error);
            }
        }];
        
        
    }
    else
    {
        AVQuery *query = [AVQuery queryWithClassName:@"LLT_VideoModel"];
        [query whereKey:@"cuserName" equalTo:[AVUser currentUser].mobilePhoneNumber];
        [query whereKey:@"title" equalTo:self.videoModel.title];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (!error) {
                for (AVObject *object in objects) {
                    [object deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            [self showAlert:@"提 示" andAlertString:@"取消收藏成功"];
                            [self.saveButton setImage:[UIImage imageNamed:@"cshoucang"] forState:UIControlStateNormal];
                            self.isCollect = NO;
                        }
                    }];
                }
                
            } else {
                // 输出错误信息
                //NSLog(@"Error: %@ %@", error, [error userInfo]);
            }
        }];

    }
    
    
}

/**
 * @brief 判断是否包含这部视频
 */
-(void)containsTheVideos
{
    AVQuery *query = [AVQuery queryWithClassName:@"LLT_VideoModel"];
    
    if ([AVUser currentUser].mobilePhoneNumber.length <= 0) {
        return;
    }
    [query whereKey:@"cuserName" equalTo:[AVUser currentUser].mobilePhoneNumber];
    [query whereKey:@"title" equalTo:self.videoModel.title];
    
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            for (int i = 0; i < objects.count; i ++) {
                NSDictionary *dic = objects[i][@"localData"];
                LLT_VideoModel *model = [[LLT_VideoModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [self.data addObject:model];
            }
            [self performSelectorOnMainThread:@selector(changeButton) withObject:nil waitUntilDone:NO];
        }else{
            //NSLog(@"%@",error);
        }
    }];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
